package com.lobaby.tools.common.utils;

import com.lobaby.tools.common.properties.SystemParamKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 *         Created by Administrator on 2019/11/26 0026.
 */
@Component
public class UploadUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(UploadUtil.class);

    // 设备上传附件路径
    public final static String SOFTWARE = "software";

    public final static String HOMEPATH = "/file/";

    @Autowired
    public static SystemParamKey systemParamKey;

    private static Resource filePath;

    public static void delFileDir(String sourceFilePath) {
        try {
            File sourceFile = new File(sourceFilePath);

            if (sourceFile.isDirectory()) {
                if (sourceFile.listFiles().length > 0) {
                    File[] listFiles = sourceFile.listFiles();
                    for (int i = 0, n = listFiles.length; i < n; i++) {
                        delFileDir(listFiles[i].getAbsolutePath());
                    }
                    sourceFile.delete();
                } else {
                    sourceFile.delete();
                }
            } else {
                sourceFile.delete();
            }
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }

    public static List<MultipartFile> getFiles(HttpServletRequest request) {
        List<MultipartFile> result = new ArrayList<>();
        if (request instanceof StandardMultipartHttpServletRequest) {
            MultiValueMap<String, MultipartFile> multiFileMap = ((StandardMultipartHttpServletRequest) request).getMultiFileMap();
            for (String key : multiFileMap.keySet()) {
                List<MultipartFile> multipartFiles = multiFileMap.get(key);
                result.addAll(multipartFiles);
            }
        }
        return result;
    }

    public static boolean isHasFile(HttpServletRequest request, String fileId) {
        if (request instanceof StandardMultipartHttpServletRequest) {
            List<MultipartFile> files = ((StandardMultipartHttpServletRequest) request).getFiles(fileId);
            if (files != null && files.size() > 0) {
                for (int i = 0; i < files.size(); i++) {
                    MultipartFile file = files.get(i);
                    try {
                        int available = file.getInputStream().available();
                        if (available > 0) {
                            return true;
                        } else {
                            if (i == files.size() - 1) {
                                return false;
                            }
                        }
                    } catch (IOException e) {
                        LOGGER.error("",e);
                    }
                }
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    /**
     * 上传文件大小限制
     *
     * @param maxFileSize
     * @return
     */
    public static boolean fileSizeIsLegal(HttpServletRequest request, String maxFileSize, String fileID) {
        if (request instanceof StandardMultipartHttpServletRequest) {
            List<MultipartFile> files = ((StandardMultipartHttpServletRequest) request).getFiles(fileID);
            for (MultipartFile file : files) {
                long fileSize = file.getSize();
                LOGGER.debug("=====> 上传文件大小: " + fileSize + "字节");

                long maxSize = Integer.parseInt(maxFileSize.substring(0, maxFileSize.indexOf("M"))) * 1024 * 1024;
                LOGGER.debug("=====> 上传文件限制大小: " + maxSize + "字节");

                return fileSize < maxSize;
            }
        }
        return true;
    }

    /**
     * 文件上传
     *
     * @param file
     * @param path
     * @return
     */
    public static String upload(MultipartFile file, String path) {
        String filePath = "";
        // 文件上传操作
        if (file != null) {
            String fileName = file.getOriginalFilename();
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            String filePrefix = fileName.substring(0, fileName.lastIndexOf("."));
            filePath = path + filePrefix + DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_YYYYMMDDSSS)
                    + fileSuffix;
            try {
                fileUpload(file.getInputStream(), filePath);
            } catch (IOException e) {
                LOGGER.error("",e);
            }
        }

        return filePath;
    }

    /**
     * 文件复制
     *
     * @param is
     * @param outPutPath
     */
    public static void fileUpload(InputStream is, String outPutPath) {
        String path = "";
        if (outPutPath.lastIndexOf("/") != -1) {
            path = outPutPath.substring(0, outPutPath.lastIndexOf("/"));
        } else {
            path = outPutPath.substring(0, outPutPath.lastIndexOf("\\"));
        }
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(new File(outPutPath));

            int len = 0;
            byte[] b = new byte[1024];
            while ((len = is.read(b)) != -1) {
                os.write(b, 0, len);
            }
        } catch (Exception e) {
            LOGGER.error("=====> Exception: " + e.getMessage());
            LOGGER.error("",e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("=====> Exception: " + e.getMessage());
                    LOGGER.error("",e);
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("=====> Exception: " + e.getMessage());
                    LOGGER.error("",e);
                }
            }
        }
    }

    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    public static boolean validateExcel(String filePath) {
        if (filePath == null || !((isExcel2003(filePath)) || (isExcel2007(filePath)))) {
            return false;
        }
        return true;
    }

    /**
     * 设备上传文件路径
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String[] uploadDevFilePath(HttpServletRequest request, String fileID) throws IOException {
        String[] filePaths = {};
        filePaths = uploadFile(request, SOFTWARE, fileID);
        return filePaths;
    }
    public static String[] uploadDevFilePath(HttpServletRequest request, String fileID, String fileName) throws IOException {
        String[] filePaths = {};
        filePaths = uploadFile(request, SOFTWARE, fileID, fileName);
        return filePaths;
    }

    public static String[] uploadDevFilePath(HttpServletRequest request, String fileID, String fileName, String approcode) throws IOException {
        String[] filePaths = {};
        filePaths = uploadFile(request, SOFTWARE, fileID, fileName, approcode);
        return filePaths;
    }

    public static String[] uploadFile(HttpServletRequest request, String filePath, String fileID) throws IOException {

        String[] filePaths = {};
		/*
		 * //获取操作人信息 User user = SessionUserUtil.getUser(); user.getName();
		 */
        if (request instanceof StandardMultipartHttpServletRequest) {
            List<MultipartFile> files = ((StandardMultipartHttpServletRequest) request).getFiles(fileID);

			/*String homeDir = systemParamKey.getFileBasePath() + HOMEPATH;*/
            filePaths = new String[files.size()];

            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
                String fileName = file.getOriginalFilename();

                String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                fileName = DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_YYYYMMDDSSS) + fileSuffix;

                // 创建文件上传根目录
                //File homeFile = new File(homeDir);
                File homeFile = UploadUtil.filePath.getFile();
                if (!homeFile.exists() && !homeFile.isDirectory()) {
                    homeFile.mkdirs();
                }
                // 创建文件上传设备目录
                File fileDev = new File(homeFile, filePath);
                if (!fileDev.exists() && !fileDev.isDirectory()) {
                    fileDev.mkdirs();
                }
                File fl = new File(fileDev, fileName);
                writeFile(fl,file.getInputStream());
                filePaths[i] = filePath+"/"+fileName/*fl.getPath()*/;
            }
        }
        return filePaths;
    }

    public static String[] uploadFile(HttpServletRequest request, String filePath, String fileID, String fileName, String approcode) throws IOException {

        String[] filePaths = {};
		/*
		 * //获取操作人信息 User user = SessionUserUtil.getUser(); user.getName();
		 */
        if (request instanceof StandardMultipartHttpServletRequest) {
            List<MultipartFile> files = ((StandardMultipartHttpServletRequest) request).getFiles(fileID);

			/*String homeDir = systemParamKey.getFileBasePath() + HOMEPATH;*/
            filePaths = new String[files.size()];

            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
                fileName = URLDecoder.decode(fileName, "UTF-8");

                String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                String filePrefix = fileName.substring(0, fileName.lastIndexOf("."));
                fileName = filePrefix + "-" + approcode + fileSuffix;

                // 创建文件上传根目录
                //File homeFile = new File(homeDir);
                File homeFile = UploadUtil.filePath.getFile();
                if (!homeFile.exists() && !homeFile.isDirectory()) {
                    homeFile.mkdirs();
                }
                // 创建文件上传设备目录
                File fileDev = new File(homeFile, filePath);
                if (!fileDev.exists() && !fileDev.isDirectory()) {
                    fileDev.mkdirs();
                }
                File fl = new File(fileDev, fileName);
                writeFile(fl,file.getInputStream());
                filePaths[i] = filePath+"/"+fileName/*fl.getPath()*/;
            }
        }
        return filePaths;
    }

    public static String[] uploadFile(HttpServletRequest request, String filePath, String fileID, String fileName) throws IOException {

        String[] filePaths = {};
		/*
		 * //获取操作人信息 User user = SessionUserUtil.getUser(); user.getName();
		 */
        if (request instanceof StandardMultipartHttpServletRequest) {
            List<MultipartFile> files = ((StandardMultipartHttpServletRequest) request).getFiles(fileID);

			/*String homeDir = systemParamKey.getFileBasePath() + HOMEPATH;*/
            filePaths = new String[files.size()];

            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
                fileName = URLDecoder.decode(fileName, "UTF-8");

                String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                String filePrefix = fileName.substring(0, fileName.lastIndexOf("."));
                fileName = filePrefix + "-" + DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_YYYYMMDDSSS)
                        + fileSuffix;

                // 创建文件上传根目录
                //File homeFile = new File(homeDir);
                File homeFile = UploadUtil.filePath.getFile();
                if (!homeFile.exists() && !homeFile.isDirectory()) {
                    homeFile.mkdirs();
                }
                // 创建文件上传设备目录
                File fileDev = new File(homeFile, filePath);
                if (!fileDev.exists() && !fileDev.isDirectory()) {
                    fileDev.mkdirs();
                }
                File fl = new File(fileDev, fileName);
                writeFile(fl,file.getInputStream());
                filePaths[i] = filePath+"/"+fileName/*fl.getPath()*/;
            }
        }
        return filePaths;
    }


    public static void writeFile(File fl,InputStream is){
        OutputStream os = null;
        try {
            os = new FileOutputStream(fl);

            int len = 0;
            byte[] b = new byte[1024];
            while ((len = is.read(b)) != -1) {
                os.write(b, 0, len);
            }
        } catch (Exception e) {
            LOGGER.error("=====> Exception: " + e.getMessage());
            LOGGER.error("",e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("=====> Exception: " + e.getMessage());
                    LOGGER.error("",e);
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("=====> Exception: " + e.getMessage());
                    LOGGER.error("",e);
                }
            }
        }
    }


    public static SystemParamKey getSystemParamKey() {
        return systemParamKey;
    }

    @Autowired
    public void setSystemParamKey(SystemParamKey systemParamKey) {
        UploadUtil.systemParamKey = systemParamKey;
    }

    @Value("${save.path.uploadsFile}")
    public void setFilePath(Resource filePath) {
        UploadUtil.filePath = filePath;
    }
}
